const cheerio = require('cheerio')
const http = require('../request/request')
const getItemMovieInfo = require('../util/getItemMovieInfo')


interface objInterface {
    playlist:Array<string>
}


interface resultObj {
    playlist:Array<string | object>,
    playIntroduce:string,
    playTitle:string,
    playCover:string,
    playStart:string,
    playType:string,
    guess:object
}

/**
 * @name getDetail
 * @description 获取详情页面文档结构
 *
 *
*/
function getDetailHtml(path:string):any{
    return new Promise(async (resolve, reject) => {
        try {
            let _html = await http.get(path)
            resolve(_html)
        } catch (err) {
            reject(err)
        }
    })
}

interface guessList {
    title:string,
    guessList:Array<object>
}
/**
 * @name guessList 猜你喜欢
 * */
function guessList ($):object{
    let result:guessList = {
        title:'',
        guessList:[]
    }
    result.title = '猜你喜欢'
    $($('.index-area')[1]).find('ul').find('li').each((idx,item)=>{
        result.guessList.push(getItemMovieInfo($,item))
    })
    return result
}

/**
 * @name getPlayPath
 * @description 获取播放地址
 * @param $  当前文档
*/
function getPlayPath($){
    let result:resultObj = {
        playlist:[],
        playIntroduce:$('.tab-jq').text() ,// 影片介绍
        playTitle:$($('.title')[0]).find('a').last().text(), // 名称
        playCover:$('.ct-l').find('img').attr('data-original'), // 封面
        playStart:$('dt').eq(1).text(), // 主演
        playType:$($('dt').eq(2).find('a')[0]).text(), // 类型
        guess:{}, // 猜你喜欢
    }
    result.guess = guessList($)
    // 剧集
    $('.playfrom').find('li').each((idx,i)=>{
        let obj:object= {}
        let play_item_title = $(i).text()
        obj['play_item_title'] = play_item_title
        obj['play_item_list'] = []
        $($('.videourl')[idx]).find('a').each((index,item) => {
            let _obj:any = {}
            let juji_title = $(item).text()
            let juji_href = $(item).attr('href')
            _obj['juji_title'] = juji_title
            _obj['juji_href'] = juji_href
            obj['play_item_list'].push(_obj)
        })
        result.playlist.push(obj)
    })
    return result
}

exports.detail = async function (req, res) {
    let path:string = req.query.path
    res.set('Cache-Control','max-age=86400')
    try {
        let {data:_html}:any = await getDetailHtml(path)
        let $ = cheerio.load(_html)
        let reslut = getPlayPath($)
        res.send({
            code:200,
            msg:'获取详情成功',
            data:reslut
        })

    }catch(err) {
        res.send({
            code:100,
            msg:err
        })
    }
};
